package com.intellagric.service.search.Impl.agriecom;

import com.intellagric.common.pojo.LayuiDataGridResult;
import com.intellagric.mapper.AgriecomProduceCategoryMapper;
import com.intellagric.pojo.AgriecomProduce;
import com.intellagric.pojo.AgriecomProduceCategory;
import com.intellagric.pojo.AgriecomProduceCategoryExample;
import com.intellagric.service.search.agriecom.AgriecomProductSearch;
import com.intellagric.service.search.dao.agriecom_product.AgriecomProductSearchDao;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

@Service
public class AgriecomProductSearchImpl implements AgriecomProductSearch {

    @Autowired
    private AgriecomProductSearchDao productSearchDao;

    @Autowired
    private AgriecomProduceCategoryMapper categoryMapper;


    private SolrQuery queryMethod(String keyword){
        SolrQuery query = new SolrQuery();
        //查询produce_name字段
        if (!keyword.equals("") && keyword != null) {
            query.set("q", keyword);
            query.set("df", "produce_name");//或者直接query.set("q","produce_name:"+keyword);
            //默认开启高亮
            query.addHighlightField("produce_name");
            query.setHighlightSimplePre("<span style='color:red;'>");
            query.setHighlightSimplePost("</span>");
        } else {
            query.set("q", "produce_name:*");
        }
        return query;
    }
    //获取categoryId下面的字类对象
    private List<AgriecomProduceCategory> children(String categoryId){
        System.out.println("ssssssssssssss");
        AgriecomProduceCategoryExample example = new AgriecomProduceCategoryExample();
        example.createCriteria().andParentIdEqualTo(categoryId);
        List<AgriecomProduceCategory> list = categoryMapper.selectByExample(example);
        if(list!=null&&list.size()!=0){
            for(AgriecomProduceCategory category:list){
                category.setChildren(children(category.getId()));
            }
            return list;
        }else
            return null;
    }
    //查找此分类（包括其子分类）下的所有商品
    private void resuleSet(AgriecomProduceCategory category,List<AgriecomProduce> list,String keyword,int page,int limit){
        if (list.size()>=(page-1)*limit+limit){
            return;                 //满足条数就退出
        }
        SolrQuery query = queryMethod(keyword);
        query.setFilterQueries("category_id:" + category.getId());
        query.setRows(Integer.MAX_VALUE);
        try {
            list.addAll(productSearchDao.keywordQuery(query).getData());
        } catch (SolrServerException e) {
            e.printStackTrace();
        }
        if(category.getChildren()!=null&&category.getChildren().size()!=0){
            for(AgriecomProduceCategory child:category.getChildren()){
                resuleSet(child,list,keyword,page,limit);
            }
        }
    }
    //获取分类下的全部数据条数
    private long getCatoryProCounts(AgriecomProduceCategory category){
        long total=productSearchDao.getCount(category.getId());
        if(category.getChildren()!=null) {
            for (AgriecomProduceCategory category1 : category.getChildren()) {
                total += getCatoryProCounts(category1);
            }
        }
        return total;
    }
    /**
     * 分类和关键字搜索、及其子类的产品
     * @param page
     * @param limit
     * @param categoryId
     * @param keyword
     * @return
     */
    @Override
    public LayuiDataGridResult keywordSearch(int page, int limit, String categoryId, String keyword) {
        if(categoryId!=null&&!categoryId.equals("")) {
            //找出父分类
            AgriecomProduceCategory category=categoryMapper.selectByPrimaryKey(categoryId);
            category.setChildren(children(categoryId));

            List<AgriecomProduce> result = new ArrayList<>();
            //查出父类、字类下的所有的产品
            resuleSet(category,result,keyword,page,limit);

            //分页
            int toIndex=result.size();

            if((page-1)*limit+limit<toIndex){//防止越界
                toIndex=(page-1)*limit+limit;
            }
            return LayuiDataGridResult.success().add(result.subList((page-1)*limit,toIndex),getCatoryProCounts(category));
        }else{//不分类时关键字搜索
            SolrQuery query = queryMethod(keyword);
            query.setStart((page-1)*limit);
            query.setRows(limit);
            try {
                LayuiDataGridResult results=productSearchDao.keywordQuery(query);
                return LayuiDataGridResult.success().add(results.getData(),results.getCount());
            } catch (SolrServerException e) {
                e.printStackTrace();
            }
            return LayuiDataGridResult.fail();
        }
    }

    @Override
    public LayuiDataGridResult addALL() {
        return productSearchDao.addALL();
    }

    @Override
    public LayuiDataGridResult paramSearch(int page, int limit, String categoryId, Map<String,String> param) {
        SolrQuery query=new SolrQuery();
        String params="*";
        if(param!=null){
            for (Map.Entry<String,String> entry:param.entrySet()){
                if(entry.getValue()!=null) {        //字符串为null时不添加条件
                    String temp;
                    if(entry.getValue().equals("全部")){  //不添加此条件
                        continue;
                    }

                    temp = "*" + entry.getKey() + "：" + entry.getValue() + "*";
                    params += temp;
                }
            }
        }
        query.set("q",params);
        query.set("df","produce_parameter");
        query.setFilterQueries("category_id:"+categoryId);
        query.setStart((page-1)*limit);
        query.setRows(limit);
        return productSearchDao.paramQuery(query);
    }
}
